﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Collections.Generic;

using Microsoft.AspNetCore.Mvc;
using ZhonTai.DynamicApi.Attributes;
using ZhonTai.Industry.Core.Consts;
using ZhonTai.Admin.Services;
using ZhonTai.DynamicApi;
using ZhonTai.Industry.Domain.WorkStation;
using ZhonTai.Industry.Services.WorkStation.Dto.Output;
using ZhonTai.Industry.Services.WorkStation.Dto.Input;
using ZhonTai.Admin.Core.Dto;
using ZhonTai.Admin.Services.Dict.Dto;
using StackExchange.Profiling.Internal;
using ZhonTai.Industry.Core.Enums;
using Microsoft.AspNetCore.Authorization;

namespace ZhonTai.Industry.Services.WorkStation
{
    /// <summary>
    /// 工站配置服务
    /// </summary>
    [Order(20)]
    [DynamicApi(Area = IndustryConsts.AreaName)]
    public class WorkStationService : BaseService, IWorkStationService, IDynamicApi
    {
        private readonly IWorkStationRepository _workStationRepository;
        private MesInit.MesInit mesInit => LazyGetRequiredService<MesInit.MesInit>();

        public WorkStationService(IWorkStationRepository workStationRepository)
        {
            _workStationRepository = workStationRepository;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<WorkStationGetOutput> GetAsync(long id)
        {
            var a = await _workStationRepository.Select
                .WhereDynamic(id)
                .Include(x => x.ProductionLine)
                .ToOneAsync(t => new WorkStationGetOutput { LineName = t.ProductionLine.LineName });
            return a;
        }

        /// <summary>
        /// 列表查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IEnumerable<WorkStationGetListOutput>> GetListAsync(WorkStationGetListInput input)
        {
            var list = await _workStationRepository.Select
                .WhereIf(input.StationCode.HasValue() && !string.IsNullOrEmpty(input.StationCode), a => a.StationCode == input.StationCode)
                .OrderBy(a => a.Sort)
                .ToListAsync(t => new WorkStationGetListOutput { LineName = t.ProductionLine.LineName });
            return list;
        }

        /// <summary>
        /// 获取启动工站
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IEnumerable<WorkStationGetListOutput>> GetActiveStationAsync()
        {
            return await _workStationRepository.Select
                .Where(x => x.Enabled)
                .OrderBy(x => x.Sort)
                .ToListAsync(t => new WorkStationGetListOutput { LineName = t.ProductionLine.LineName });
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<WorkStationGetPageOutput>> GetPageAsync(PageInput<WorkStationGetPageInput> input)
        {
            var filter = input.Filter;
            var select = _workStationRepository.Select
                .WhereDynamicFilter(input.DynamicFilter)
                .WhereIf(filter.LineId.HasValue && filter.LineId > 0, w => w.LineId == filter.LineId)
                .Count(out var total);
            if (input.SortList != null && input.SortList.Count > 0)
            {
                input.SortList.ForEach(sort =>
                {
                    select = select.OrderByPropertyNameIf(sort.Order.HasValue, sort.PropName, sort.IsAscending.Value);
                });
            }
            else
            {
                select = select.OrderBy(a => a.Sort);
            }
            var list = await select
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync<WorkStationGetPageOutput>(t => new WorkStationGetPageOutput { LineName = t.ProductionLine.LineName });
            var data = new PageOutput<WorkStationGetPageOutput>()
            {
                List = list,
                Total = total
            };
            return data;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<long> AddAsync(WorkStationAddInput input)
        {
            var entity = Mapper.Map<WorkStationEntity>(input);
            var id = (await _workStationRepository.InsertAsync(entity)).Id;

            return id;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task UpdateAsync(WorkStationUpdateInput input)
        {
            var entity = await _workStationRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                throw ResultOutput.Exception("工站配置不存在！");
            }

            Mapper.Map(input, entity);
            await _workStationRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> DeleteAsync(long id)
        {
            return await _workStationRepository.DeleteAsync(id) > 0;
        }

        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> SoftDeleteAsync(long id)
        {
            return await _workStationRepository.SoftDeleteAsync(id);
        }

        /// <summary>
        /// 批量软删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<bool> BatchSoftDeleteAsync(long[] ids)
        {
            return await _workStationRepository.SoftDeleteAsync(ids);
        }

        /// <summary>
        /// 设置启用
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SetEnableAsync(WorkStationSetEnableInput input)
        {
            var entity = await _workStationRepository.GetAsync(input.StationId);
            entity.Enabled = input.Enabled;
            if (input.Enabled)
            {
                entity.StartTime = DateTime.Now;
            }
            else
            {
                entity.EndTime = DateTime.Now;
            }
            await _workStationRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 工站通讯管理
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> SetCommStateAsync(WorkStationSetCommStateInput input)
        {
            var entity = await _workStationRepository.GetAsync(input.WorkStationId);
            if (input.State == CommEnum.Start)
            {
                await mesInit.InitAlarmErrAsync(entity);
                return await mesInit.InitProcessParmeterAsync(entity);
            }
            if (input.State == CommEnum.Stop)
            {
                await mesInit.StopAlarmErrAsync(entity);
                return await mesInit.StopProcessParmeterAsync(entity);
            }
            return false;
        }
    }
}